function getElementsByClassName (className) {
			var all = document.all ? document.all : document.getElementsByTagName('*');
			var elements = new Array();
			for (var e = 0; e < all.length; e++) {
				if (all[e].className == className) {
					elements[elements.length] = all[e];
					break;
				}
			}
			return elements;
		} 

/*
 *  ajax request
*/
	function getElements(formName) {
    	var form = document.getElementsByName(formName);
    var elements = new Array();
	var tagElements = form[0].getElementsByTagName('input');
    for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    return elements;
}

function inputSelector(element) {
  if (element.checked)
     return [element.name, element.value];
}
  
function input(element) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return [element.name, element.value];
      case 'checkbox':
      case 'radio':
        return inputSelector(element);
    }
    return false;
}


function serializeElement(element) {
    var method = element.tagName.toLowerCase();
    var parameter = input(element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];
	  
	  var values = parameter[1];
	  var results = [];
	  for (var i=0; i<values.length; i++) {
	  	results.push(key + '=' + encodeURIComponent(values[i]));
	  }
      return results.join('&');
    }
 }
  
function serializeForm(formId) {
    var elements = getElements(formId);
    var queryComponents = new Array();

    for (var i = 0; i < elements.length; i++) {
      var queryComponent = serializeElement(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }

    return queryComponents.join('&');
}

function getXMLHttpRequest(){
	var request = false;
	try {
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				request = false;
			}
		}
	}
	return request;
}
	
	function getMarkerDatas(){
		var returnValue = getMarkerDatByFormInfo(); 
		if(returnValue){
			return eval(returnValue);
			
		}else{
			alert("该区域没有楼盘");
			return;
		}
	}
	
	/***
	 * 
	 * @return
	 */
	function getMarkerDatByFormInfo() {
		var request = getXMLHttpRequest();
		
		var formName = 'mapInfoForm';
		var postBody = serializeForm(formName);
		var forms = document.getElementsByName(formName);
		var url = forms[0].action;
//		var formId = 'mapInfoForm';
//		var postBody = serializeForm(formId);
//		var url = document.getElementById(formId).action;
		request.open("post", url, false);
//		request.open("post", url, true);
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		request.send(postBody);
		return request.responseText;
	}
	
	function getHouseList(buildingId) {
		var request = getXMLHttpRequest();
		
		var formName = 'houseForm';
		var form = document.getElementById(formName);
		form.buildingId.value = buildingId;
		var postBody = serializeForm(formName);
		var url = form.action;
		request.open("post", url, false);

		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		
		request.send(postBody);
		
		return request.responseText;
	}
/**
 * 地图
 * 
 */

function ComplexCustomOverlay(point, text, mouseoverText,buildingId){
	this._bId = buildingId;
	this._point = point;
    this._text = text;
    this._overText = mouseoverText;
  };
  ComplexCustomOverlay.prototype = new BMap.Overlay();
  
  ComplexCustomOverlay.prototype.initialize = function(map){
	      this._map = map;
	      var div = this._div =  document.createElement("div");
	      
	      var div2 = document.createElement("div");
	      this._div.appendChild(div2);
	      
	      this._div.id = "marker" ;
	      this._div.className = "marker" ;
	      this._div.style.display = "block";
	      div2.className = "marker_bg";
	
	      
	      var strong = document.createElement("strong");
 	      div2.appendChild(strong);	      
 	      strong.appendChild(document.createTextNode(this._text));  
	      
	      var that = this;

	      this._div.onmouseover = function(){
	    	 div.className += " marker_hover" ;
	    	 this.getElementsByTagName("strong")[0].innerHTML += that._overText;
	     };
	      this._div.onmouseout = function(){
	    	 div.className = "marker" ; 
	    	 this.getElementsByTagName("strong")[0].innerHTML = that._text;
	     };
	  
	      map.getPanes().labelPane.appendChild(div);

	      return div;
	    };
	    
	    ComplexCustomOverlay.prototype.draw = function(){
	      var map = this._map;
	      var pixel = map.pointToOverlayPixel(this._point);
	      
	      this._div.style.left = pixel.x  + "px";
	      this._div.style.top  = pixel.y  + "px";
    
	     
	    };
	    
	    ComplexCustomOverlay.prototype.addEventListener = function(event,fun){
	        this._div['on'+event] = fun;
	    };



    //创建地图函数：
    function createMap(center,zoom){
        var map = new BMap.Map("container");//在百度地图容器中创建一个地图
        map._infowindow = map._infowindow ||null;
        var defaultPoint = center ||new BMap.Point(113.263549 , 23.127099 );
        var defaultZoom = zoom||12 ;
 //       var point = new BMap.Point(113.385643,23.166129);//定义一个中心点坐标
        map.centerAndZoom(defaultPoint,defaultZoom);//设定地图的中心点和坐标并将地图显示在地图容器中
        map.infowindowHtml = '<div id="baidu_map_propwin" class="baidu_map_propwin" style="top: 38px; left: 291px; display:none;">'+
			'<h2 id="baidu_map_propwin_header" class="h2title baidu_win_bg link_white"><a id="baidu_map_propwin_close" href="javascript:;" title="关闭" class="title_close baidu_win_bg04"></a>'+
				'<span class="h2title_commname"></span>'+
				'<a id="winCommTitleLink" class="h2title_listlink" target="_blank" href="#">查看小区详情&gt;&gt;</a>'+
			'</h2>'+
			'<div id="baidu_map_propwin_content" class="content">'+
				'<div class="prowin_left">'+
					'<h5 class="left_h5title">按租金筛选:</h5>'+
					'<dl id="win_filters_price" class="left_dl_list dl_height100">'+
					'</dl>'+
					'<dl id="win_filters_model" class="left_dl_list">'+
						'<dt>按房型筛选:</dt>'+
					'</dl>'+
					'<dl id="win_filters_source" class="left_dl_list dl_bor_none">'+
						'<dt>按来源筛选:</dt>'+
					'</dl>'+
				'</div>'+
				'<div class="prowin_right">'+
					'<div class="top_title baidu_win_bg04">'+
						'<ul class="top_title_ul">'+
							'<li class="li_num">'+
								'找到<strong class="c_ora_red">0</strong>套房子'+
							'</li>'+
							'<li class="li_fiter">'+
								'<input id="map2_is_hq" type="checkbox" name="frm_ishq">'+
								'<label for="map2_is_hq">多图房源</label>'+
							'</li>'+
							'<li class="li_fiter">'+
								'<input id="map2_is_hd" type="checkbox" name="frm_ishd">'+
								'<label for="map2_is_hd">高清大图房源</label>'+
							'</li>'+
							'<li id="propSort" class="li_sort">'+
								'<span>排序：</span>'+
								'<a class="sort_button baidu_win_bg04" rel="0" href="javascript:;">租金</a>'+
							'</li>'+
						'</ul>'+
					'</div>'+
				'<div class="map2_propwind_load" style="display:none;">'+
					'<img src="http://pages.haozu.ajkcdn.com/20120313/img/map/load_18x18.gif" alt="loading..." />'+
				'</div>'+
				'<div id="propWinNonProps" style="display: none;">'+
					'<p>'+
						'很抱歉，没有找到符合条件的房源。'+
					'</p>'+
					'<p>'+
						'<strong>建议您：</strong><br />'+
						'重新选择房源筛选条件。'+
					'</p>'+
					'<p class="red">'+
						'&lt;--就在左边'+
					'</p>'+
				'</div>'+
				'<ul class="property_list">'+
				'</ul>'+
				'<div class="clear"></div>'+
				'<div id="map2_info_page" style="">'+
					'<div class="page_prev" style="visibility: hidden;">上一页</div>'+
					'<div class="page_next" style="visibility: visible;">下一页</div>'+
					'<span class="c_gray9">1/32</span>'+
				'</div>'+
				'</div>'+
				'<div class="clear"></div>'+
			'</div>'+
			'<div class="bg_bot baidu_win_bg"></div>'+
		'</div>';
        window.map = map;//将map变量存储在全局
    }
    
    //地图事件设置函数：
    function setMapEvent(){
        map.enableDragging();//启用地图拖拽事件，默认启用(可不写)
        map.setMinZoom(12);    // 地图允许的最小级别
        map.setMaxZoom(18);    // 地图允许的最大级别
        map.enableScrollWheelZoom();//启用地图滚轮放大缩小
        map.disableContinuousZoom(); //禁止连续缩放
        map.enableDoubleClickZoom();//启用鼠标双击放大，默认启用(可不写)
        map.enableKeyboard();//启用键盘上下左右键移动地图
    }
    
    //地图控件添加函数：
    function addMapControl(){
        //向地图中添加缩放控件
	var ctrl_nav = new BMap.NavigationControl({anchor:BMAP_ANCHOR_TOP_LEFT,type:BMAP_NAVIGATION_CONTROL_SMALL});
	map.addControl(ctrl_nav);
        //向地图中添加缩略图控件
//	var ctrl_ove = new BMap.OverviewMapControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,isOpen:1});
//	map.addControl(ctrl_ove);
        //向地图中添加比例尺控件
	var ctrl_sca = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT});
	map.addControl(ctrl_sca);
    }
    
    function addMarker(data,map){
    	 var txt = data.houses.length + "套", mouseoverTxt =  " "+ data.name ;
	        var lng = data.lng ;
			var lat = data.lat;
			
			var bId = data.buildingId;
	        var myCompOverlay = new ComplexCustomOverlay(new BMap.Point(lng,lat), txt,mouseoverTxt,bId);
	       
	        map.addOverlay(myCompOverlay);
	        myCompOverlay.addEventListener('click',function(e){ 
	        	var rs = "("+  getHouseList(myCompOverlay._bId) + ")";
	        	//alert(rs);
	        	var html = getInfoWindowHtml(eval(rs),myCompOverlay._overText,5000);
		        
	        
	        	
		        var infoWindow = new sksMap.ExtInfoWindow(map,html,{
		        	windowStyle:{
		        			background:"url('/map/resource/infowindow/tipbox.gif') no-repeat center top"
		        			//,width: "648px"
		        			//,height: "450px"
		        		}
		        		,closeIconMargin: "1px 8px 0 0"
		        });
	        	infoWindow.open(myCompOverlay);
	        });
    }	
    
    function updateMarker(datas){
    	if(map){
    		map.clearOverlays();
    		for(var i = 0 ; i< datas.length ; i++){
    	       addMarker(datas[i],map);
    		}
    	}
    }
    
    /**
     * 将当前鼠标位置设置为地图中心
     * */
    function setCurrentPositionAsCenter(point){
    	if(map && point){
    		map.setCenter(point);
    	}
    }
    
    /**
     * 返回可视区域的地理坐标
     * @return
     */
    function getBounds(){
    	return map!=null ? map.getBounds():null; 
    }
    /**
     * 拼接信息窗口的html
     * rs:含分页信息和房源信息的字符串
     */
    function getInfoWindowHtml(rs,windowTitle,avePrice){
    	var houseLs = eval("("+rs.resultSet+")");
    	var totalPages = rs.totalPages;
    	var html = "<div class='infoWindow'><div class='title'><strong>"+windowTitle+"</strong></div>";//+"</strong><span class='price'>"+"均价："+ avePrice+"</span></div>";
    	html += getHouseListHtml(houseLs);
    	//设置弹出窗口的房源列表的记录数
    	setHouseListTotalPages("houseForm",rs.totalPages);

    	//visibilty:hidden
            html += "<div class='clear'></div>" +
            "<div class='map2_info_page' style='display: block;'><div class='page_prev' onclick='page_pre(\"houseForm\");' style='visibility: hidden;'>上一页</div>"+
            "<div class='page_next' onclick='page_next(\"houseForm\");' style='visibility: visible;'>下一页</div>"+
       //     "<span class="c_gray9">1/19</span>"+
            "</div>"
            ,"</div>";
            return html;
    	
    	
    }
    
    function initMap(center,zoom,datas){
        createMap(center,zoom);//创建地图
        setMapEvent();//设置地图事件
        addMapControl();//向地图添加控件
    
        updateMarker(datas);
        
        map.addEventListener('zoomend',function(e){
        	var bound  = getBounds();
        	document.getElementsByName("sw").value = bound.getSouthWest();
        	document.getElementsByName("ne").value = bound.getNorthEast();
        	
       	   var updataDatas = getMarkerDatas();
       	   if(updataDatas){
       		   //alert("get return value");
       		   updateMarker(updataDatas);
       	   }
        });
        
        map.addEventListener('dragend',function(){
        	var bound  = getBounds();
         	var sw = bound.getSouthWest();
         	var ne = bound.getNorthEast();
    	//	alert(sw.lng + " , " + sw.lat);
        //	alert(ne.lng + " , " + ne.lat);
        	/*
        	 * 赋值给 'mapInfoForm'相应的field
        	 */
        	if(!sw|| !ne){
        		alert("sw is null");
        	}
        	document.getElementById("sw").value = sw.lng + '|' + sw.lat;
        	document.getElementById("ne").value = ne.lng + '|' + ne.lat;

        	var updataDatas = getMarkerDatas();
        	   if(updataDatas){
        		   //alert("get return value");
        		   updateMarker(updataDatas);
        	   }
        });
   }
    
	function localSearch(keyWords,round){
		var local = new BMap.LocalSearch(map, {
     	   renderOptions:{map: map, autoViewport:true}
     	});
		var key = keyWords.split(",");
		if(key.length > 0){
			var myJs = "local.searchNearby(";
			keyWords = "";
			for(var i = 0 ; i<key.length; i++){
				keyWords = keyWords + "\"" + key[i] + "\",";
			}
			myJs = local.searchNearby(keyWords,map.getCenter(),round);
			eval(myJs);			
		}
		
		 
	}
	
	
	/**
	 * infoWindow分页
	 */
	function page_pre(formName){
		var form = document.forms[formName];
		var element = null;
		var pageNo = oldPageNo = form.page.value;
		var pageTotal = form.totalPages.value;
		if(parseInt(pageNo)-1 < 1){
			//pageNo = 1;
			element = getElementsByClassName("page_prev");
			element[0].style.visibility="hidden";
		}else{
			pageNo = parseInt(pageNo)-1;
			form.page.value = pageNo;
			
			element = getElementsByClassName("page_next");
			element[0].style.visibility="visible";
			
			var html_new =getInfowindowHouseList(formName);
			//更新列表div
			var div = document.getElementById("mapList");
			div.innerHTML = html_new;
		}
		
	}
	
	function page_next(formName){
				
		var form = document.forms[formName];
		var element = null;
		//当前页码
		var pageNo = oldPageNo = form.page.value;
		//总页数
		var pageTotal = form.totalPages.value;
		
		if(parseInt(pageNo)+1 > pageTotal){
			pageNo = pageTotal;
			element = getElementsByClassName("page_next");
			element[0].style.visibility="hidden";
			
		}else{
			pageNo = parseInt(pageNo)+1;
			form.page.value = pageNo;
			
			element = getElementsByClassName("page_prev");
			element[0].style.visibility="visible";
			
			var html_new =getInfowindowHouseList(formName);
			//更新列表div
			var div = document.getElementById("mapList");
			div.innerHTML = html_new;
		}
		
				
		
	}
	
	function setHouseListTotalPages(formName,totalPages){
		var form = document.forms[formName];
		//总页数
		form.totalPages.value = totalPages;
		
	}
	function getInfowindowHouseList(formName){
		var request = getXMLHttpRequest();
		var postBody = serializeForm(formName);
		
		var url = document.forms[formName].action;
		request.open("post", url, false);
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		
		request.send(postBody);
		
		var rs = eval("("+request.responseText+")");
		setHouseListTotalPages("houseForm",rs.totalPages);
		return getHouseListHtml(eval(rs.resultSet));
		 
		
	}
	/***
	 * 根据json数据构造房源列表的html
	 * @param houseLs
	 * @return
	 */
	function getHouseListHtml(houseLs){
		  var html = "<div class='list' id=\"mapList\"><ul>";
          var len = houseLs.length;
          for(var i=0;i<len;i++){
          	var house = houseLs[i];
          	var title = house.title||"";
          	if(title&&title.length>17){
          		title = title.substring(0,17) + "...";
          	}
          	var space = house.space?"  "+house.space+"平方米":"";
          	var floorAt = house.floorAt?"  "+house.floorAt+"层":"";
          	//var img = "/map/resource/house3.jpg";
          	var img="";//这里可以使用一个默认图片，"no photoes"
          	if(house && house.pictures[0]){
          		var picture = house.pictures[0];
          		img = "/"+picture.path + "/" + picture.name+"."+picture.extension;
          	}
          	var houseType ="";
          	if(house.houseType){
          		houseType = house.houseType.name||"";
          	}
          	var price = "";
          	//transaStatus 0是出租，1是出售，2是租售均可
          	//TODO
          	//出租出售的价格的单位
              //图片的路径
          	//房源明显的url
          	if(house.transaStatus ==1){
          		price = house.salePrice?"  "+house.salePrice+"元/平方米":"";
          	}else{
          		price = house.rentPrice?"  "+house.rentPrice+"元/月":"";
          	}
          	var url = "/sks/house.do?method=info&houseId="+ house.houseId;
          	
          	html +="<li><div class='left'><img src='";
          	html +=img;
          	html +="'/></div>";
          	html +="<div class='left'><a target='_blank' href='";
          	html +=url;
          	html +="'>";
          	html += title;
          	html +="</a><p>"+houseType+" "+ space +""+floorAt+"</p></div>";
          	html +="<div class='rmb'>"+price+"</div></li>";
             
          }
          html += "</ul></div>";
          return html;
	
	}

	